package com.rtech.app.client;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;

public class RestResponseErrorHandler implements ResponseErrorHandler {

	private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
	protected static Logger logger = Logger
			.getLogger("RestResponseErrorHandler");

	@Override
	public boolean hasError(ClientHttpResponse response) throws IOException {
		return errorHandler.hasError(response);
	}

	@Override
	public void handleError(ClientHttpResponse response) throws IOException {
		HttpStatus statusCode = response.getStatusCode();
		System.out.println(statusCode.value());
		String str = IOUtils.toString(response.getBody(), "UTF-8");
		System.out.println(str);
		try {
			errorHandler.handleError(response);
		} catch (RestClientException e) {
			logger.info(e.getMessage());
			throw new ServiceException(str);
		}

	}
}
